package ar.tuc.unsta.campus.weather.unstaWeatherUpload.view.util;

import java.io.File;

import org.apache.commons.vfs2.FileChangeEvent;
import org.apache.commons.vfs2.FileListener;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.VFS;
import org.apache.commons.vfs2.impl.DefaultFileMonitor;

import sun.reflect.generics.reflectiveObjects.NotImplementedException;

public class FileWatcher implements FileListener{

	private DefaultFileMonitor fileMonitor = null;
	
	public void listenToFile(File fileToUpload) throws FileSystemException, InterruptedException{
		FileSystemManager fsManager = VFS.getManager();
		FileObject fileObject = fsManager.toFileObject(fileToUpload);
		if(fileMonitor == null){
			fileMonitor = new DefaultFileMonitor(this);
			fileMonitor.addFile(fileObject);
			fileMonitor.start();
		}
		synchronized(this) {
			this.wait(); //wait fileChange
			this.listenToFile(fileToUpload); //recursive call
		}
	}
	
	public void fileChanged(FileChangeEvent fce) throws Exception {
		System.out.println("File "+fce.getFile()+" has changed.");
		synchronized(this){
			this.notify();
		}
	}
	
	public void stopListening(){
		if(fileMonitor != null)
			fileMonitor.stop();
	}

	public void fileCreated(FileChangeEvent paramFileChangeEvent)
			throws Exception {
		throw new NotImplementedException();
	}

	public void fileDeleted(FileChangeEvent paramFileChangeEvent)
			throws Exception {
		throw new NotImplementedException();
	}

}
